/*
 * @Author: szx
 * @Date: 2022-02-27 13:18:01
 * @LastEditTime: 2022-02-27 13:44:50
 * @Description:
 * @FilePath: \leetcode\剑指offer\67\67.JS
 */
/**
 * @param {string} str
 * @return {number}
 */
 var strToInt = function (str) {
    let nege = 0;
    let num = 0;
    let firstEmpty = 0;
    for (let s of str) {
        if (s == ' ') {
            if (firstEmpty == 0) continue;
            else break;
        } else if (s == '-') {
            if (nege == 0 && firstEmpty == 0) {
                nege = -1;
                firstEmpty = 1;
                continue;
            } else break;
        } else if (s == '+' && firstEmpty == 0) {
            if (nege == 0) {
                nege = 1;
                firstEmpty = 1;
                continue;
            } else break;
        } else if (s <= '9' && s >= '0') {
            num *= 10;
            num += parseInt(s);
            firstEmpty = 1;
        } else {
            break;
        }
    }
    if (nege >= 0) return num > 2147483647 ? 2147483647 : num;
    else return -num < -2147483648 ? -2147483648 : -num;
};
console.log(strToInt('42'));
console.log(strToInt('   -42'));
console.log(strToInt('4193 with words'));
console.log(strToInt('words and 987'));
console.log(strToInt('-91283472332'));
console.log(strToInt('+1'));
console.log(strToInt('+0 123'));
console.log(strToInt('0-1'));
console.log(strToInt('-5-'));
